<template>
  <div class="contest-details">
    <!-- 返回按钮 -->
    <el-button type="default" @click="goBack">返回</el-button>
    <h2>{{ contest.name }}</h2>

    <!-- 比赛的时间信息 -->
    <div class="contest-time">
      <p>开始时间: {{ formatDate(contest.startTime) }}</p>
      <p>结束时间: {{ formatDate(contest.endTime) }}</p>

      <!-- 动态滑动条 -->
      <el-slider
        v-model="sliderValue"
        :min="0"
        :max="100"
        :step="1"
        :show-tooltip="true"
        label="比赛进行进度"
        :format-tooltip="formatSliderTooltip"
        disabled
      ></el-slider>
      <p>已过时间：{{ elapsedTimeFormatted }}</p>
    </div>

    <!-- 排行榜按钮 -->
    <el-button type="primary" @click="viewLeaderboard">查看排行榜</el-button>

    <!-- 题目列表 -->
    <div class="problem-list">
      <el-table
        :data="problems"
        @row-click="handleProblemClick"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
       
      >
        <el-table-column
          prop="problemId"
          label="题目编号"
          width="150"
        ></el-table-column>
        <el-table-column prop="problemTitle" label="题目标题"></el-table-column>
        <el-table-column
          prop="submitCount"
          label="提交量"
          width="120"
        ></el-table-column>
        <el-table-column
          prop="correctCount"
          label="正确数"
          width="120"
        ></el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.isSolved ? 'success' : 'danger'">
              {{ row.isSolved ? "✔ 已解决" : "❌ 未解决" }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from "vue";
import {
  ElSlider,
  ElTable,
  ElTableColumn,
  ElButton,
  ElMessage,
} from "element-plus";
import request from "@/utils/request";

export default {
  data() {
    return {
      contest: {}, // 当前比赛的信息
      problems: [], // 当前比赛的题目信息
      sliderValue: 0, // 滑动条值
      timer: null, // 定时器引用，用于清理定时器
    };
  },
  mounted() {
    const contestId = this.$route.params.id; // 从路由中获取比赛ID
    this.fetchContestDetails(contestId); // 获取比赛详情
    // 定时器更新滑动条
    this.timer = setInterval(this.updateSlider, 1000); // 每秒更新一次
  },
  beforeUnmount() {
    // 清理定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    // 获取比赛详情
    fetchContestDetails(contestId) {
      request
        .get(`/contest/selectById?id=${contestId}`)
        .then((res) => {
          if (res && res.data) {
            this.contest = res.data;
            if (this.contest.status === 0) {
              this.$router.push("/");
              ElMessage.error("比赛未开放");
            }
            this.fetchProblems(contestId);
            this.updateSlider(); // 初始更新进度滑动条
          }
        })
        .catch((error) => {
          ElMessage.error("加载比赛详情失败");
        });
    },
    
    // 获取比赛题目列表
    fetchProblems(contestId) {
      request
        .get(`/contest/${contestId}/questions`)
        .then((res) => {
          if (res && res.data) {
            this.problems = res.data;
            const userId = this.$store.state.user?.user?.id; // 从 Vuex 获取当前用户的名称
            const startTime = this.contest.startTime
            const checkStatusPromises = this.problems.map(async (problem) => {
              try {
                // 获取该题目对应的提交状态和提交信息
                const result = await request.get(
                  `/contest/selectAllSubmission/${contestId}/${problem.problemId}/${userId}`,
                  { params: { startTime: startTime } } // 传入比赛开始时间
                );
                // 处理返回的状态和提交数据
                if (result.code === "200" && result.data) {
                  const { submitTimes, timeUsage } = result.data;
                  problem.isSolved = timeUsage >= 0; // 直接修改属性，不需要 $set
                } else {
                  problem.isSolved = false; // 没有解决
                }
              } catch (error) {
                problem.isSolved = false; // 请求失败时，假定未解决
              }
            });
            // 等待所有的检查状态请求完成
            Promise.all(checkStatusPromises).then(() => {
              this.problems = [...this.problems]; // 强制更新
            });
          }
        })
        .catch((error) => {
          ElMessage.error("加载题目列表失败");
        });
    },

    // 格式化日期时间
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleString();
    },

    // 格式化滑动条提示
    formatSliderTooltip(value) {
      return `${value}%`;
    },

    updateSlider() {
      const currentTime = new Date();
      const startTime = new Date(this.contest.startTime);
      const endTime = new Date(this.contest.endTime);

      const totalDuration = endTime - startTime;
      const elapsedTime = currentTime - startTime;

      // 如果比赛尚未开始
      if (elapsedTime < 0) {
        this.sliderValue = 0;
        this.elapsedTimeFormatted = "尚未开始";
      }
      // 如果比赛已经结束
      else if (elapsedTime > totalDuration) {
        this.sliderValue = 100;
        this.elapsedTimeFormatted = this.formatElapsedTime(totalDuration); // 总时长
      }
      // 比赛进行中
      else {
        this.sliderValue = (elapsedTime / totalDuration) * 100;
        this.elapsedTimeFormatted = this.formatElapsedTime(elapsedTime); // 已经过的时间
      }
    },

    // 格式化已过时间（以小时:分钟显示）
    formatElapsedTime(timeInMillis) {
      const hours = Math.floor(timeInMillis / 3600000);
      const minutes = Math.floor((timeInMillis % 3600000) / 60000);
      return `${hours}小时 ${minutes}分钟`;
    },
    // 跳转到排行榜页面
    viewLeaderboard() {
      const contestId = this.contest.id;
      this.$router.push(`/contest/leaderboard/${contestId}`);
    },
    // 跳转到题目页面
    handleProblemClick(row) {
      const contestId = this.contest.id; // 当前比赛的ID
      const problemId = row.problemId; // 当前题目的ID
      const status = this.contest.status;
      this.$router.push(
        `/challenge/${problemId}?contestId=${contestId}&status=${status}`
      );
    },
    // 返回到比赛列表页面
    goBack() {
      this.$router.push("/contest"); // 跳转到/contest
    },
  },
};
</script>

<style scoped>
.contest-details {
  width: 80%;
  margin: 0 auto;
  padding: 20px;
}

.contest-time {
  margin-bottom: 20px;
}

h2 {
  font-size: 28px;
  margin-bottom: 20px;
}

.el-slider {
  width: 100%;
  margin-top: 20px;
}

.el-button {
  margin-top: 20px;
}

.problem-list {
  margin-top: 20px;
}

.el-table {
  margin-top: 10px;
}
</style>
